<?php

namespace app\models;

use app\librarys\DbCacheUtility;
use app\librarys\getui\GetuiClient;
use app\librarys\Tools;

class User
{
    const SessionKey = 'session_key_user';
    const UserTokenCacheKey = 'user_token:';
    const UserTokenExpiresIn = 60 * 60 * 24 * 7;  // user token 过期时间为7天
    const MaterialGiftCash = 6; //完善资料单个红包金额
    const ShareGiftCash = 6; //分享红包单个金额
    const RegisterGiftCash = 6;//注册红包

    /**
     * 获取当前登录用户(如果为null,则未登录)
     * @return mixed|null
     */
    public static function getCurrentUser()
    {
        if (\Yii::$app->session->has(self::SessionKey)) {
            $item = \Yii::$app->session->get(self::SessionKey);
            return $item;
        }
        if (YII_DEBUG) {
            $item = self::getById('525aca26-76be-11e7-84d9-00163e06b8e1'); //调试默认使用525aca26-76be-11e7-84d9-00163e06b8e1 user账号
            return $item;
        }

        return null;
    }

    /**
     * 返回所有设置了经纬度的用户
     * @return mixed
     */
    public static function getAllUser()
    {
        $cmd = \Yii::$app->db->createCommand('select id,phone,lat,lon from t_user where !ISNULL(lon) and !ISNULL(lat)');

        $result = DbCacheUtility::queryAll($cmd);
        return $result;
    }

    public static function updateTourist($user_id, $isTourist)
    {
        $cmd = \Yii::$app->db->createCommand('update t_user set isTourist=:isTourist where id=:id');
        $cmd->bindValue(':id', $user_id);
        $cmd->bindValue(':isTourist', $isTourist);

        $result = DbCacheUtility::execute($cmd);
        return $result;
    }

    /**
     * 用户登录以后,设置到session中
     * @param $user
     */
    public static function setCurrentUser($user)
    {
        \Yii::$app->session->remove(self::SessionKey);
        \Yii::$app->session->set(self::SessionKey, $user);
    }

    public static function getByPhone($phone)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_user where phone=:phone');
        $cmd->bindValue(':phone', $phone);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    /**
     * 用户注册
     * @param $phone
     * @return false|null|string
     */
    public static function register($phone)
    {
        $id = Tools::db_uuid();
        $cmd = \Yii::$app->db->createCommand('insert into t_user(id, phone) values(:id, :phone);');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':phone', $phone);
        $result = DbCacheUtility::execute($cmd);


        if ($result > 0) {
            //调用注册奖励
//            self::presentRegistGift($id,RegisterGiftCash);
            return $id;
        } else {
            return null;
        }
    }

    public static function login($phone)
    {
        $item = self::getByPhone($phone);
        if ($item != null) {
            $userToken = self::_setUserToken($item['id']);
            $item['token'] = $userToken;
            self::setCurrentUser($item);
        }
        return $item;
    }

    private static function _setUserToken($userId)
    {
        // 设置token之前,先将此userId用户以前所用的token清除,已保证每个用户同时只有一个token有效。
        $userIdCacheKey = self::UserTokenCacheKey . $userId;
        $tokenCacheKey = \Yii::$app->cache->get($userIdCacheKey);
        if ($tokenCacheKey != false) {
            \Yii::$app->cache->delete($tokenCacheKey);
        }
        \Yii::$app->cache->delete($userIdCacheKey);

        $userToken = Tools::uuid();
        $tokenCacheKey = self::UserTokenCacheKey . $userToken;

        \Yii::$app->cache->set($userIdCacheKey, $tokenCacheKey, self::UserTokenExpiresIn);
        \Yii::$app->cache->set($tokenCacheKey, $userId, self::UserTokenExpiresIn);

        return $userToken;
    }

    public static function authUserToken($userToken)
    {
        $tokenCacheKey = self::UserTokenCacheKey . $userToken;
        $userId = \Yii::$app->cache->get($tokenCacheKey);
        if ($userId == false) {
            return null;
        }

        $userIdCacheKey = self::UserTokenCacheKey . $userId;
        \Yii::$app->cache->set($userIdCacheKey, $tokenCacheKey, self::UserTokenExpiresIn);
        \Yii::$app->cache->set($tokenCacheKey, $userId, self::UserTokenExpiresIn);

        return $userId;
    }

    // region 用户管理
    public static function getCount()
    {
        $cmd = \Yii::$app->db->createCommand('select count(1) from t_user');
        $count = DbCacheUtility::queryScalar($cmd);
        return $count;
    }

    public static function getList($page, $pageSize)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_user ORDER BY create_datetime DESC limit :offset , :limit');
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
        $items = DbCacheUtility::queryAll($cmd);
        return $items;
    }

    public static function getById($id)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_user where id=:id');
        $cmd->bindValue(':id', $id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    public static function bandPushId($userId, $push_id)
    {
        $cmd = \Yii::$app->db->createCommand('update t_user set push_id=:push_id where id=:user_id');
        $cmd->bindValue(':user_id', $userId);
        $cmd->bindValue(':push_id', $push_id);
        $item = DbCacheUtility::execute($cmd);
        return $item;
    }

    /**
     * 修改用户信息
     * @param $id
     * @param $name
     * @param $nick_name
     * @param $phone
     * @param $gravatar
     * @param $gender
     * @param $birthday
     * @param $occupation
     * @param $company
     * @param $school
     * @param $hobby
     * @param $tag
     * @return bool
     */
    public static function save($id, $name, $nick_name, $phone, $gravatar, $gender, $birthday, $occupation, $company, $school, $hobby, $tag)
    {
        $sql = 'UPDATE t_user SET name = :name, nick_name = :nick_name, phone = :phone, 
                      gravatar = :gravatar, gender = :gender, birthday = :birthday, occupation = :occupation, 
                      company = :company, school = :school, hobby = :hobby, tag = :tag
                WHERE id = :id';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':name', $name);
        $cmd->bindValue(':nick_name', $nick_name);
        $cmd->bindValue(':phone', $phone);
        $cmd->bindValue(':gravatar', $gravatar);
        $cmd->bindValue(':gender', $gender);
        $cmd->bindValue(':birthday', $birthday);
        $cmd->bindValue(':occupation', $occupation);
        $cmd->bindValue(':company', $company);
        $cmd->bindValue(':school', $school);
        $cmd->bindValue(':hobby', $hobby);
        $cmd->bindValue(':tag', $tag);
        $cmd->bindValue(':id', $id);

        return DbCacheUtility::execute($cmd) > 0;
    }
    // endregion

    /**
     * region 提现
     * **/
    public static function getEnchashmentRecordCount()
    {
        $cmd = \Yii::$app->db->createCommand('select count(1) from t_user_account_enchashment_auth_record');
        $count = DbCacheUtility::queryScalar($cmd);
        return $count;
    }

    public static function getEnchashmentRecordList($page, $pageSize)
    {
        $cmd = \Yii::$app->db->createCommand('
            select t0.*, t1.`name`, t1.nick_name, t1.phone from t_user_account_enchashment_auth_record t0
            LEFT join t_user t1 on t1.id=t0.user_id
            order by t0.create_datetime DESC LIMIT :offset , :limit');
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
        $items = DbCacheUtility::queryAll($cmd);
        return $items;
    }

    public static function getEnchashmentRecordDetail($id)
    {
        $cmd = \Yii::$app->db->createCommand('
            select t0.*, t1.`name`, t1.nick_name, t1.phone, t2.amount as user_account from t_user_account_enchashment_auth_record t0
            LEFT join t_user t1 on t1.id=t0.user_id
            LEFT join t_user_account t2 on t2.user_id=t0.user_id
            where t0.id=:id');
        $cmd->bindValue(':id', $id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    public static function enchashmentSuccess($id, $remark)
    {
        $result = 0;
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $cmd = \Yii::$app->db->createCommand('call p_enchashment_auth_success(:id, :remark);');
            $cmd->bindValue(':id', $id);
            $cmd->bindValue(':remark', $remark);
            $result = DbCacheUtility::queryScalar($cmd);

            $transaction->commit();
        } catch (\Exception $ex) {
            $transaction->rollBack();
            $result = 1;
            throw $ex;
        }

        return $result;
    }

    public static function enchashmentFailed($id, $remark)
    {
        $cmd = \Yii::$app->db->createCommand('UPDATE t_user_account_enchashment_auth_record SET `status`=2, remark=:remark WHERE id=:id;');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':remark', $remark);
        DbCacheUtility::execute($cmd);
    }


    /**
     * 设置用户位置
     * @param $id
     * @param $lon
     * @param $lat
     * @return int
     */
    public static function setUserPosition($id, $lon, $lat)
    {

        $cmd = \Yii::$app->db->createCommand('
            update t_user set lon = :lon,lat=:lat where id = :id');
        $cmd->bindValue(':lon', $lon);
        $cmd->bindValue(':lat', $lat);
        $cmd->bindValue(':id', $id);
//        var_dump($cmd->rawSql);
        $items = DbCacheUtility::execute($cmd);
        return $items;

    }

    public static function getAdsByArea($id, $lon, $lat, $search_range)
    {
        $squares = Tools::returnSquarePoint($lon, $lat, $search_range);

        $rl = $squares['right-bottom']['lat'];
        $ll = $squares['left-top']['lat'];
        $ltl = $squares['left-top']['lng'];
        $rbl = $squares['right-bottom']['lng'];


        $sql = 'select t1.id,t1.title,t1.content,t1.lon,t1.lat,t2.one_cash,t5.`name` as industry_name,t4.url,IFNULL(t6.`status`,1) as `status` from
                 `t_ad` t1 left join t_ad_cash_gift t2 on t1.id=t2.ad_id 
                 LEFT JOIN t_ad_image t3 ON t3.ad_id=t1.id 
                 LEFT JOIN t_file t4 on t4.id=t3.image_id 
                left JOIN t_ad_industry_type t5 on t5.id = t1.industry_type_id
                left join t_ad_cash_gift_users t6 on t6.ad_id=t1.id and t6.user_id=:user_id
                 where t1.lat<>0 and t1.lat>:rl and t1.lat<:ll and t1.lon>:ltl and t1.lon<:rbl and t2.pay_status=1 and t1.end_datetime>=now() and t3.`type`=1';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':rl', $rl);
        $cmd->bindValue(':ll', $ll);
        $cmd->bindValue(':ltl', $ltl);
        $cmd->bindValue(':rbl', $rbl);
        $cmd->bindValue(':user_id', $id);

        //        var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryAll($cmd);
        return $item;
    }

    public static function getAd($ad_id)
    {
        $sql = 'select t1.merchant_id,t1.title,date(t1.publish_datetime) as `date`,t1.id,t1.content,t2.`name` as industry_name,t3.consume_times,t1.video from t_ad t1 
                LEFT JOIN t_ad_industry_type t2 on t2.id = t1.industry_type_id
                LEFT JOIN t_ad_times t3 on t3.ad_id=t1.id
                where t1.id=:ad_id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
//        var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        if (is_null($item) && is_null($item['consume_times']))
            $item['consume_times'] = 0;

        //添加阅读次数
        $sql = 'select times from t_ad_times where ad_id=:ad_id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
        $times = DbCacheUtility::queryScalar($cmd);
//        var_dump($times);
        if (is_null($times)) {
            $sql = 'insert into t_ad_times (ad_id,times,consume_times)VALUES (:ad_id,:times,0)';
            $times = 1;
        } else {
            $sql = 'update t_ad_times set times =:times where ad_id=:ad_id';
            $times = $times + 1;
        }
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
        $cmd->bindValue(':times', $times);
        $times = DbCacheUtility::execute($cmd);

        return $item;
    }

    /**
     * 获得商家详情
     * @param $mershant_id
     * @return mixed
     */
    public static function getMerchat($mershant_id)
    {
        $sql = 'select `name`,gravatar,tel,province,city,county,address,lon,lat,url from t_merchant
                where id=:id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $mershant_id);
//        var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    /**
     * 收藏商家
     * @param $user_id
     * @param $merchant_id
     * @return int|null
     */
    public static function keepMerchant($user_id, $merchant_id)
    {
        $cmd = \Yii::$app->db->createCommand('
           select * from t_user_merchant_follow where user_id=:user_id and merchant_id=:merchant_id');
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':merchant_id', $merchant_id);
        //$cmd->bindValue(':id',$id);
        //var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null) {
            return null;
        }

        $cmd = \Yii::$app->db->createCommand('
           insert into t_user_merchant_follow(user_id,merchant_id)VALUES (:user_id,:merchant_id)');
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':merchant_id', $merchant_id);
        //$cmd->bindValue(':id',$id);
//        var_dump($cmd->rawSql);
        $items = DbCacheUtility::execute($cmd);
        return $items;
    }

    /**
     * 收藏广告
     * @param $user_id
     * @param $ad_id
     */
    public static function keepAd($user_id, $ad_id)
    {
        $cmd = \Yii::$app->db->createCommand('
           select * from t_user_ad_follow where user_id=:user_id and ad_id=:ad_id');
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':ad_id', $ad_id);
        //$cmd->bindValue(':id',$id);
        //var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null) {
            $cmd = \Yii::$app->db->createCommand('
           insert into t_user_ad_follow(user_id,ad_id)VALUES (:user_id,:ad_id)');
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':ad_id', $ad_id);
            //$cmd->bindValue(':id',$id);
            return DbCacheUtility::execute($cmd) > 0;
        } else {
            return null;
        }
    }

    /**
     * 举报广告
     * @param $user_id
     * @param $ad_id
     */
    public static function accuseAd($user_id, $ad_id)
    {
        $cmd = \Yii::$app->db->createCommand('
           select * from t_user_ad_accuse where user_id=:user_id and ad_id=:ad_id');
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':ad_id', $ad_id);
        //$cmd->bindValue(':id',$id);
        //var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null) {
            $cmd = \Yii::$app->db->createCommand('
           insert into t_user_ad_accuse(user_id,ad_id)VALUES (:user_id,:ad_id)');
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':ad_id', $ad_id);
            //$cmd->bindValue(':id',$id);
            DbCacheUtility::execute($cmd);
        }
    }

    /**
     * 获取红包领取次数
     * @param $ad_id
     * @return mixed
     */
    public static function getGiftTimes($ad_id)
    {
        $cmd = \Yii::$app->db->createCommand('select count(user_id) as times from t_ad_cash_gift_users where `status`=2 and ad_id=:ad_id');
        $cmd->bindValue(':ad_id', $ad_id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    /**
     * 获取广告口令
     * @param $ad_id
     * @return mixed
     */
    public static function getWord($ad_id)
    {
        $cmd = \Yii::$app->db->createCommand('select question,answer_right,answer_error from t_ad_cash_gift where ad_id=:ad_id');
        $cmd->bindValue(':ad_id', $ad_id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    /**
     * @param $ad_id
     * @param $user_id
     * @return mixed
     */
    public static function getGiftCash($ad_id, $user_id)
    {
        $cmd = \Yii::$app->db->createCommand('select `status` from t_ad_cash_gift_users where ad_id=:ad_id and user_id =:user_id ');
        $cmd->bindValue(':ad_id', $ad_id);
        $cmd->bindValue(':user_id', $user_id);
        //  var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);

        return $item;
    }

    public static function getTotalGift($user_id)
    {
        $cmd = \Yii::$app->db->createCommand('select sum(one_cash) as `total` from t_ad_cash_gift t1 left join t_ad_cash_gift_users t2 on t1.ad_id = t2.ad_id where user_id =:user_id and t2.status=2');
//        $cmd->bindValue(':ad_id',$ad_id);
        $cmd->bindValue(':user_id', $user_id);
        //  var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        // var_dump('item:'.$item);
        return $item;
    }

    public static function getMyGiftList($user_id)
    {
        $cmd = \Yii::$app->db->createCommand('select t1.id,t1.title,t2.`status`,t3.`name`,t5.url,t6.consume_times from t_ad t1 left join t_ad_cash_gift_users t2 on t1.id=t2.ad_id
 left join t_ad_industry_type t3 on t3.id = t1.industry_type_id
 left join t_ad_image t4 on t4.ad_id = t1.id
 left join t_file t5 ON t5.id = t4.image_id
 left JOIN t_ad_times t6 on t6.ad_id=t1.id
 where t2.user_id=:user_id and t4.type = 1 and (t2.`status`=1 or t2.`status`=2)');
//        $cmd->bindValue(':ad_id',$ad_id);
        $cmd->bindValue(':user_id', $user_id);
//          var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryAll($cmd);
        return $item;
    }

    /**
     * 是否已经领取过红包
     * @param $user_id
     * @param $ad_id
     * @return mixed ture 领取过 ；false 未领取
     */
    public static function isGotGift($user_id, $ad_id)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_ad_cash_gift_users where user_id=:user_id and ad_id=:ad_id and `status`=2');
        $cmd->bindValue(':ad_id', $ad_id);
        $cmd->bindValue(':user_id', $user_id);
        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null) {
            return false;
        }
        return true;

    }

    /**
     * 获取红包
     * @param $user_id
     * @param $ad_id
     */
    public static function getGift($user_id, $ad_id, $word)
    {
//        $cmd = \Yii::$app->db->createCommand('select t1.user_id from t_ad_cash_gift t0 LEFT JOIN t_ad_cash_gift_users t1 on t1.ad_id=t0.ad_id
//        where t0.ad_id=\'da75e3dc-a6ae-11e7-84d9-00163e06b8e1\' and t0.publish_type=2 and t0.pay_status=1 ');
//        $cmd->bindValue(':ad_id', $ad_id);
//        $cmd->bindValue(':user_id', $user_id);
//        $t = DbCacheUtility::queryScalar($cmd);
//
//        if($t == null){
//            $cmd = \Yii::$app->db->createCommand('insert into t_ad_cash_gift_users(id,user_id,ad_id,`status`)VALUES (uuid(),:user_id,:ad_id,0)');
//            $cmd->bindValue(':ad_id', $ad_id);
//            $cmd->bindValue(':user_id', $user_id);
//            var_dump($cmd->rawSql);
//            $t = DbCacheUtility::execute($cmd);
//        }

        $cmd = \Yii::$app->db->createCommand('select ifnull(user_id,0) from t_user_account where user_id=:user_id');
        $cmd->bindValue(':user_id', $user_id);

        $te = DbCacheUtility::queryScalar($cmd);

        if($te == null || $te ==0)
        {
            try {
                $cmd = \Yii::$app->db->createCommand('insert into t_user_account(user_id, `amount`) values(:id, 0);');
                $cmd->bindValue(':id', $user_id);
                DbCacheUtility::execute($cmd);
            }catch (\Exception $ex){}

        }

        $cmd = \Yii::$app->db->createCommand('select ifnull(id,0) from t_ad_question_user_relation where user_id=:user_id and ad_id=:ad_id');
        $cmd->bindValue(':ad_id', $ad_id);
        $cmd->bindValue(':user_id', $user_id);
//var_dump($cmd->rawSql);
        $tempp = DbCacheUtility::queryScalar($cmd);
        if($tempp != 0){
             $item['status']=5;
            $item['message']='亲，红包需要认真';
            return $item;
        }

        $cmd = \Yii::$app->db->createCommand('call p_get_gift(:ad_id,:user_id,:word)');
        $cmd->bindValue(':ad_id', $ad_id);
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':word', $word);
//var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        if($item['status']==1){//ok
            $cmd = \Yii::$app->db->createCommand('select ad_id from t_ad_times where ad_id=:ad_id');
            $cmd->bindValue(':ad_id', $ad_id);
            $id = DbCacheUtility::queryScalar($cmd);
            $sql = '';
//            var_dump("id:$id");
            if ($id == $ad_id) {
                $sql = 'update t_ad_times set consume_times=consume_times+1 where ad_id=:ad_id';
            } else {
                $sql = 'insert into t_ad_times(ad_id,times,consume_times)VALUES (:ad_id,0,1)';
            }
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad_id);
             DbCacheUtility::execute($cmd);
        }elseif ($item['status']==4){//回答错误
            $iiid = Tools::db_uuid();
            $sql = 'insert into t_ad_question_user_relation(id,ad_id,user_id)VALUES (:id,:ad_id,:user_id)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $iiid);
            $cmd->bindValue(':ad_id', $ad_id);

            $cmd->bindValue(':user_id', $user_id);

            DbCacheUtility::execute($cmd);
        }
        // var_dump('item'.$item);
        return $item;

    }

    /**
     * 更新用户
     * @param $id
     * @param $nick_name
     * @param $gravatar
     * @param $gender
     * @param $birthday
     * @param $occupation
     * @param $company
     * @param $school
     * @param $hobby
     * @param $tag
     * @return bool
     */
    public static function updateUser($id, $nick_name, $gravatar, $gender, $birthday, $occupation, $company, $school, $hobby, $tag)
    {
        $sql = 'UPDATE t_user SET nick_name = :nick_name, 
                      gravatar = :gravatar, gender = :gender, birthday = :birthday, occupation = :occupation, 
                      company = :company, school = :school, hobby = :hobby, tag = :tag
                WHERE id = :id';

        $cmd = \Yii::$app->db->createCommand($sql);
//        $cmd->bindValue(':name', $name);
        $cmd->bindValue(':nick_name', $nick_name);
//        $cmd->bindValue(':phone', $phone);
        $cmd->bindValue(':gravatar', $gravatar);
        $cmd->bindValue(':gender', $gender);
        $cmd->bindValue(':birthday', $birthday);
        $cmd->bindValue(':occupation', $occupation);
        $cmd->bindValue(':company', $company);
        $cmd->bindValue(':school', $school);
        $cmd->bindValue(':hobby', $hobby);
        $cmd->bindValue(':tag', $tag);
        $cmd->bindValue(':id', $id);

        $re = DbCacheUtility::execute($cmd);

        //调用资料完善奖励
        self::presentMaterialGift($id, self::MaterialGiftCash);


        return $re;
    }

    /**
     * 获取收藏广告列表
     * @param $page
     * @param $pageSize
     * @param $user_id
     * @return mixed
     */
    public static function getAdFollowList($page, $pageSize, $user_id)
    {
        $sql = 'SELECT t1.id,t1.`title`,t3.url,t4.`name` from t_user_ad_follow t0
                        LEFT join t_ad t1 on t1.id=t0.ad_id
                        LEFT JOIN t_ad_image t2 on t2.ad_id=t1.id AND t2.`type`=1
                        LEFT JOIN t_file t3 on t3.id = t2.image_id
                        LEFT JOIN t_ad_industry_type t4 on t4.id=t1.industry_type_id
                        where t0.user_id=:userId
                        limit :offset, :limit';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':userId', $user_id);
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
//        var_dump($cmd->rawSql);

        return DbCacheUtility::queryAll($cmd);
    }

    /**
     * 获取收藏商家列表
     * @param $page
     * @param $pageSize
     * @param $user_id
     * @return mixed
     */
    public static function getMerchantFollowList($page, $pageSize, $user_id)
    {
        $sql = 'SELECT t1.id,t1.`name`,t1.gravatar,t1.province,t1.city,t1.county,t1.address from t_user_merchant_follow t0
                        LEFT join t_merchant t1 on t1.id=t0.merchant_id
                        where t0.user_id=:userId
                        limit :offset, :limit';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':userId', $user_id);
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
//        var_dump($cmd->rawSql);
        return DbCacheUtility::queryAll($cmd);
    }

    /**
     * 获取红包列表
     * @param $user_id
     * @return mixed
     */
    public static function getGiftList($user_id)
    {
        $sql = 'select t2.ad_id,t2.`status`,title from t_ad_cash_gift_users t1 left JOIN t_ad t2 on t1.ad_id=t2.ad where t2.user_id=:user_id';

        $cmd = \Yii::$app->db->createCommand($sql);
//        $cmd->bindValue(':name', $name);

        $cmd->bindValue(':user_id', $user_id);
        $items = DbCacheUtility::queryAll($cmd);
        foreach ($items as &$item) {
            $item['main_image_url'] = self::getAdMainImage($item['ad_id']);
        }

        return $items;
    }

    public static function getAdMainImage($ad_id)
    {
        $sql = 'select t2.url from t_ad_image t1 left JOIN t_file t2 on t1.image_id = t2.id where t1.ad_id=:ad_id and t1.`type`=1';

        $cmd = \Yii::$app->db->createCommand($sql);
//        $cmd->bindValue(':name', $name);

        $cmd->bindValue(':ad_id', $ad_id);

        return DbCacheUtility::queryOne($cmd);
    }
    // endregion

    /**
     * 意见
     * @param $userId
     * @param $feedback
     * @return false|null|string
     */
    public static function feedback($userId, $feedback)
    {
        $sql = 'INSERT INTO t_feedback(id, content, origin, origin_id)
                      VALUES(:id, :content, 2, :originId)';

        $id = Tools::db_uuid();
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':content', $feedback);
        $cmd->bindValue(':originId', $userId);

        DbCacheUtility::execute($cmd);

        return $id;
    }

    public static function getMygroupList($userId)
    {
        $sql = 'select * from t_group t1 LEFT JOIN t_group_user_relation t2 on t1.id = t2.group_id where t2.user_id= :id ';

//        $id = Tools::db_uuid();
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $userId);
//        $cmd->bindValue(':content', $feedback);
//        $cmd->bindValue(':originId', $userId);

        $item = DbCacheUtility::queryAll($cmd);

        return $item;
    }

    /**
     * 查询用户余额
     * @param $user_id
     */
    public static function queryUserMoeny($user_id)
    {
        $sql = 'select amount from t_user_account where user_id= :id ';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $user_id);
//        $cmd->bindValue(':cash', $cash);
//        $cmd->bindValue(':wish_type', $wish_type);

        $item = DbCacheUtility::queryScalar($cmd);
        return $item;
    }


    public static function setMoneyPassword($user_id, $password)
    {
        $sql = 'select * from t_user_account where user_id= :id ';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $user_id);
//        var_dump($cmd->rawSql);

        $item = DbCacheUtility::queryOne($cmd);

        if ($item != null) {
            $sql = 'update t_user_account set password=:password where user_id= :id ';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $user_id);
            $cmd->bindValue(':password', md5($password));
//        $cmd->bindValue(':wish_type', $wish_type);
//            var_dump($cmd->rawSql);

            return DbCacheUtility::execute($cmd) > 0;
        } else {
            $sql = 'insert into t_user_account(user_id,amount,password)VALUES (:id,0,:password)';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $user_id);
            $cmd->bindValue(':password', md5($password));
//        $cmd->bindValue(':wish_type', $wish_type);
//            var_dump($cmd->rawSql);
            return DbCacheUtility::execute($cmd) > 0;
        }
    }

    /**
     * 添加提现申请记录
     * @param $user_id
     * @param $cash
     * @param $wish_type
     * @param $account
     * @return mixed
     */
    public static function applyWishdrawCash($user_id, $cash, $wish_type, $account)
    {

        $id = Tools::db_uuid();
        $sql = 'insert into t_user_account_enchashment_auth_record (id,user_id,`type`,account,amount,`status`)VALUES (:id,:user_id,:wish_type,:account,:cash,0)';


        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':cash', $cash);
        $cmd->bindValue(':wish_type', $wish_type);
        $cmd->bindValue(':account', $account);

        $item = DbCacheUtility::execute($cmd);
        return $item;
    }

    /**
     * 判断密码是否相等
     * @param $password
     * @param $user_id
     * @return bool
     */
    public static function verifyPassword($password, $user_id)
    {
        $sql = 'select password from t_user_account where user_id=:id';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $user_id);
//        $cmd->bindValue(':password', $password);
        $item = DbCacheUtility::queryScalar($cmd);
        return $item == md5($password);

    }

    public static function getUserNames($user_id)
    {
        $sql = 'select nick_name,gravatar from t_user where id=:id';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $user_id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    public static function getUser($user_id)
    {
        $sql = 'select id,phone,lat,lon,nick_name,gravatar,gender,birthday,occupation,company,school,hobby,tag from t_user where id=:id';

        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $user_id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    public static function addAdData()
    {
        $sql = 'select id from t_ad';

        $cmd = \Yii::$app->db->createCommand($sql);

        $items = DbCacheUtility::queryAll($cmd);

        foreach ($items as $item) {

            $transaction = \Yii::$app->db->beginTransaction();
            try {
                $address = 'http://lizhimedia.oss-cn-shanghai.aliyuncs.com/1503997783838.png';
                $sql = 'insert into t_file (id,url)VALUES (:id,:address)';
                $id = Tools::db_uuid();
                $cmd = \Yii::$app->db->createCommand($sql);
                $cmd->bindValue(':id', $id);
                $cmd->bindValue(':address', $address);
                $result = DbCacheUtility::execute($cmd);

                $id2 = Tools::db_uuid();
                $sql = 'insert into t_ad_image(id,ad_id,image_id)VALUES (:id,:ad_id,:tid)';
                $cmd = \Yii::$app->db->createCommand($sql);
                $cmd->bindValue(':id', $id2);
                $cmd->bindValue(':ad_id', $item['id']);
                $cmd->bindValue(':tid', $id);

                $result = DbCacheUtility::execute($cmd);


                $transaction->commit();
            } catch (\Exception $ex) {
                $transaction->rollBack();
                $result = 1;
                throw $ex;
            }
        }
    }

    public static function addShareRecord($user_id, $title, $share_type)
    {
        $sql = 'insert into t_share_record (id,title,user_id,share_type)VALUES (:id,:title,:user_id,:share_type)';
        $id = Tools::db_uuid();
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':title', $title);
        $cmd->bindValue('share_type', $share_type);

        $item = DbCacheUtility::execute($cmd);
        return $item;
    }

    public static function updateTags($user_id, $tags)
    {
        $sql = 'update t_user set tag=:tags where id=:user_id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':tags', $tags);

        $item = DbCacheUtility::execute($cmd);
        return $item;
    }

    public static function updateHobbys($user_id, $hobbys)
    {
        $sql = 'update t_user set hobby=:hubby where id=:user_id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':user_id', $user_id);
        $cmd->bindValue(':hubby', $hobbys);

        $item = DbCacheUtility::execute($cmd);
        return $item;
    }

    /**
     * 赠送用户money
     * @param $user_id
     * @param $cash 赠送完善资料金额
     */
    static function presentMaterialGift($user_id, $cash)
    {
        $result = 0;
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $sql = 'select material_gift_total from t_user where id=:user_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':user_id', $user_id);
            $total = DbCacheUtility::queryScalar($cmd);
//            var_dump(self::MaterialGiftCash);exit();

            if (($total + $cash) > self::MaterialGiftCash) {
                return -1;//超过可发金额，不发
            }


            $sql = 'UPDATE t_user SET material_gift_total=:cash+material_gift_total WHERE id = :user_id';

            $cmd = \Yii::$app->db->createCommand($sql);
//        $cmd->bindValue(':name', $name);
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':cash', $cash);

            DbCacheUtility::execute($cmd);

            $sql = 'UPDATE t_user_account SET amount=:cash+amount WHERE user_id=:user_id';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':cash', $cash);

            DbCacheUtility::execute($cmd);

            $id = Tools::db_uuid();
            $sql = 'insert into t_user_account_record (id,user_id,amount,`type`,origin_id)VALUES (:id,:user_id,:cash,101,:user_id)';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $id);
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':cash', $cash);

            DbCacheUtility::execute($cmd);


            $transaction->commit();


            $sql = 'select push_id from t_user where id=:user_id ';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':user_id', $user_id);

            $push_id = DbCacheUtility::queryScalar($cmd);
            if ($push_id != null) {
                GetuiClient::pushMessageToSingle($push_id, '恭喜您获得完成完善资料任务奖励，6元已经到账，清查收！');
            } else {
                GetuiClient::pushMessageToSingleWithLog($push_id, '恭喜您获得完成完善资料任务奖励，6元已经到账，清查收！', '[presentMaterialGift]; user_id:' . $user_id);
            }
        } catch (\Exception $ex) {
            $transaction->rollBack();
            $result = 1;
            throw $ex;
        }
        return $result;
    }


    /**
     * 赠送注册任务金额
     * @param $user_id
     * @param $cash
     * @return int
     * @throws \Exception
     */
    static function presentRegistGift($user_id, $cash)
    {
        $result = 0;
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $sql = 'select register_gift_total from t_user where id=:user_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':user_id', $user_id);
            $total = DbCacheUtility::queryScalar($cmd);
//            var_dump(self::MaterialGiftCash);exit();

            if (($total + $cash) > self::RegisterGiftCash) {
                return -1;//超过可发金额，不发
            }


            $sql = 'UPDATE t_user SET register_gift_total=:cash+register_gift_total WHERE id = :user_id';

            $cmd = \Yii::$app->db->createCommand($sql);
//        $cmd->bindValue(':name', $name);
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':cash', $cash);

            DbCacheUtility::execute($cmd);

            $sql = 'UPDATE t_user_account SET amount=:cash+amount WHERE user_id=:user_id';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':cash', $cash);

            DbCacheUtility::execute($cmd);

            $id = Tools::db_uuid();
            $sql = 'insert into t_user_account_record (id,user_id,amount,`type`,origin_id)VALUES (:id,:user_id,:cash,100,:user_id)';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $id);
            $cmd->bindValue(':user_id', $user_id);
            $cmd->bindValue(':cash', $cash);

            DbCacheUtility::execute($cmd);


            $transaction->commit();

            $sql = 'select push_id from t_user where id=:user_id ';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':user_id', $user_id);

            $push_id = DbCacheUtility::queryScalar($cmd);
            if ($push_id != null) {
                GetuiClient::pushMessageToSingle($push_id, '恭喜您获得完成注册任务奖励，6元已经到账，清查收！');
            } else {
                GetuiClient::pushMessageToSingleWithLog($push_id, '恭喜您获得完成注册任务奖励，6元已经到账，清查收！', '[presentRegistGift]; user_id:' . $user_id);
            }
        } catch (\Exception $ex) {
            $transaction->rollBack();
            $result = 1;
            throw $ex;
        }
        return $result;
    }

    public static function updateUserAge()
    {
        $sql = 'select birthday,id from t_user  ';
        $cmd = \Yii::$app->db->createCommand($sql);

        $users = DbCacheUtility::queryAll($cmd);
        foreach ($users as $user) {
            $sql = 'update t_user set age=IFNULL(DATEDIFF(NOW(),birthday),1) div 365 where id=:user_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':user_id', $user['id']);
            echo 'update user:' . $user['id'] . ' age.';
            $item = DbCacheUtility::execute($cmd);

        }

    }


    public static function log($content, $class_name)
    {
        $id = Tools::db_uuid();
        $sql = 'insert into t_log (id,content,class_name)VALUES (:id,:content,:class_name)';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':content', $content);
        $cmd->bindValue(':class_name', $class_name);

//        var_dump($cmd->rawSql);
        $item = DbCacheUtility::execute($cmd);
    }


}
